/**
 * created by jsq on 2017/11/9
 * 2018/12/20优化代码
 */
import React from 'react'
import {connect} from 'react-redux'
import {messages} from "share/common";
import {Button, Table, Badge} from 'antd';
import SearchArea from 'components/search-area';
import menuRoute from 'routes/menuRoute'
import 'styles/setting/department-group/department-group.scss';
import deptGroupService from 'containers/setting/department-group/dept-group.service'
import ImportModal from "components/template/import-modal-ie/import-modal";
import config from "config";
import ResizeTable from "components/resize-table";

class DepartmentGroup extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: true,
      data: [],
      searchParams: {
        deptGroupCode: "",
        name: ""
      },
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      searchForm: [
        {
          type: 'input',
          id: 'deptGroupCode',
          label: messages('setting.key478'/*部门组代码*/)
        },
        {
          type: 'input',
          id: 'name',
          label: messages('setting.key479'/*部门组名称*/)
        },
      ],
      columns: [
        {
          title: messages('setting.key478'/*部门组代码*/),
          key: "deptGroupCode",
          dataIndex: 'deptGroupCode'
        },
        {
          title: messages('setting.key479'/*部门组名称*/),
          key: "name",
          dataIndex: 'name'
        },

        {
          title: messages('common.column.status'),
          key: 'status',
          width: '10%',
          dataIndex: 'enabled',
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages('common.status.enable') : messages('common.status.disable')}/>
          )
        },
        {
          title: messages('setting.key1147')/*操作*/, dataIndex: 'operation', width: '10%',
          render: (text, record) => (
            <div>
              <a onClick={(e) => this.handleEdit(e, text, record)}> {messages('setting.key1071')/*编辑*/}&nbsp;&nbsp;
              </a>
              <a onClick={(e) => this.handleRowClick(e, text, record)}> {messages('setting.key202')/*详情*/}
              </a>
            </div>
          ),
        }
      ],
    }
  }

  componentWillMount() {
    //记住页码
    let _pagination = this.getBeforePage();
    let pagination = this.state.pagination;
    pagination.page = _pagination.page;
    pagination.current = _pagination.page + 1;
    this.setState({
      pagination,
    }, () => {
      this.clearBeforePage();
      this.getList();
    })
  }

  //获取部门组数据
  getList() {
    this.setState({loading: true});
    const {searchParams, pagination} = this.state;
    let params = Object.assign({}, this.state.searchParams);
    params.page = pagination.page;
    params.size = pagination.pageSize;
    deptGroupService.getDeptGroupByOptions(params).then((response) => {
      response.data.map((item, index) => {
        item.key = item.id;
      });
      let pagination = this.state.pagination;
      pagination.total = Number(response.headers['x-total-count']);
      this.setState({
        data: response.data,
        pagination,
        loading: false
      })
    })
  };

  handleSearch = (values) => {
    let searchParams = {
      deptGroupCode: !values.deptGroupCode ? "" : values.deptGroupCode,
      name: !values.name ? "" : values.name
    };
    let pagination = this.state.pagination;
    pagination.page = 0;
    pagination.pageSize = 10;
    pagination.current = 1;
    this.setState({
      searchParams,
      pagination,
      loading: true,
      page: 1
    }, () => {
      this.getList();
    })
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
        total: pagination.total
      }
    }, () => {
      this.getList();
    })
  };

  //新建公司组
  handleCreate = () => {
    this.setBeforePage(this.state.pagination);
    this.context.router.push(menuRoute.getMenuItemByAttr('department-group', 'key').children.newDepartmentGroup.url);
  };

  //编辑公司组
  handleEdit = (e, text, record) => {
    this.setBeforePage(this.state.pagination);
    this.context.router.push(menuRoute.getRouteItem('edit-department-group', 'key').url.replace(":id", record.id));
  };
  //点击行，进入该行详情页面
  handleRowClick = (e, text, record) => {
    this.setBeforePage(this.state.pagination);
    let url = menuRoute.getMenuItemByAttr('department-group', 'key').children.departmentGroupDetail.url;
    url = url.replace(':id', record.id);
    this.context.router.push(url);
  };

  render() {
    const {searchForm, loading, data, columns, pagination} = this.state;
    return (
      <div className="budget-structure">
        <SearchArea searchForm={searchForm} submitHandle={this.handleSearch} clearHandle={() => {
        }}/>
        <div className="table-header">
          <div className="table-header-title">
            {/*共搜索到*条数据*/}
            {messages('common.total', {total: `${pagination.total}`})}
          </div>
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleCreate}>
              {/*新 建*/}
              {messages('common.create')}
            </Button>
            <ImportModal downLinks={null}
                         hasErrInfo={true}
                         uploadUrl={`${config.baseUrl}/api/DepartmentGroup/import?${this.props.tenantMode ? 'roleType=TENANT' : ""}`}
                         showErrUrl={`${config.baseUrl}` + "/api/batch/transaction/logs/v2/${transactionOID}"}
                         exportErrUrl={`${config.baseUrl}` + "/api/DepartmentGroup/error/export?transactionOID=${transactionOID}"}
                         onCancel={this.getList}
                         templates={[
                           {
                             downloadName: messages('setting.key1985')/*下载部门组导入模板*/,
                             templateName: messages('setting.key1986')/*部门组导入模板*/,
                             downloadUrl: "/api/DepartmentGroup/template",
                             downloading: "departmentLoading"
                            },
                           {
                             downloadName: messages('setting.key1987')/*下载部门组明细导入模板*/,
                             templateName: messages('setting.key1988')/*部门组明细导入模板*/,
                             downloadUrl: "/api/DepartmentGroupDetail/template",
                             downloading: "departmentGroupLoading"
                           }
                         ]}/>
            &nbsp; &nbsp; &nbsp;
          </div>
        </div>
        <ResizeTable
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={pagination}
          onChange={this.onChangePager}
          size="middle"
          bordered
        />
      </div>
    )
  }
}

DepartmentGroup.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

export default connect(mapStateToProps)(DepartmentGroup);
